package com.yunxiao.cloud.oss.util;

import org.apache.hadoop.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;

/**
 * @description: 文件工具类
 * @date: 2019/12/18 11:14
 * @author: yunxiao
 * @version: 1.0
 */
public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    private FileUtil() {
        // to do nothing
    }

    /**
     * 文件写入输入流
     * @param in 输入流
     * @param file 文件
     */
    private static void inputStreamToFile(InputStream in, File file) {
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            int bytesRead;
            int bufferSize = 8*1024;
            byte[] buffer = new byte[bufferSize];
            while ((bytesRead = in.read(buffer, 0, bufferSize)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            logger.error("【文件写入输入流失败】", e);
        } finally {
            IOUtils.closeStream(in);
            IOUtils.closeStream(outputStream);
        }
    }

    /**
     * MultipartFile 转 File
     * @param multipartFile 上传的文件
     * @return
     */
    public static File multipartFileToFile(MultipartFile multipartFile) {
        File file = null;
        try {
            if (multipartFile != null && multipartFile.getSize() > 0) {
                InputStream inputStream = multipartFile.getInputStream();
                file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
                inputStreamToFile(inputStream, file);
            }
        } catch (IOException e) {
            logger.error("MultipartFile 转 File", e);
        }
        return file;
    }
}
